const express = require('express');
const router = express.Router();
const dao = require('../dao/mysql/ProductsDao');
const pager = require('../util/PagerHelper.js');
const multer = require('multer');
const fs = require('fs');
let fileAddress = null;

// 使用硬盘存储模式设置存放接收到的文件的路径以及文件名
let storage = multer.diskStorage({
	destination: function (req, file, cb) {
		// 接收到文件后输出的保存路径（若不存在则需要创建）
		cb(null, 'public/images/');
	},
	filename: function (req, file, cb) {
		// 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
		fileAddress = 'http://120.24.89.102:8081/public/images/' + Date.now() + '-' + file.originalname;
		cb(null, Date.now() + '-' + file.originalname);
	},
});

//添加配置文件到muler对象。
var upload = multer({
	storage: storage,
});

router.all('/list.do', async (req, res, next) => {
	let where = '';
	let flag = 0; //控制多条件是否要加and
	if (req.body) {
		console.log('req.body', req.body);
		if (req.body.uname) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			where += `uname like '%${req.body.uname}%' `;
			flag++;
		}
		if (req.body.id) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` p.id = '${req.body.id}' `;
			flag++;
		}
		if (req.body.uid) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` uid = '${req.body.uid}' `;
			flag++;
		}
		if (req.body.pname) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` pname like '%${req.body.pname}%' `;
			flag++;
		}
		if (req.body.cgname) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` cgname like '%${req.body.cgname}%' `;
			flag++;
		}
		if (req.body.cid) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` cid = ${req.body.cid} `;
			flag++;
		}
		if (req.body.ishot) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` ishot = ${req.body.ishot} `;
			flag++;
		}
		if (req.body.isgood) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` isgood = ${req.body.isgood} `;
			flag++;
		}
		if (req.body.pprice) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` pprice = '${req.body.pprice}' `;
			flag++;
		}
		if (req.body.state || req.body.state == 0) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` state = '${req.body.state}' `;
			flag++;
		}
		if (req.body.selled || req.body.selled == 0) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` selled = '${req.body.selled}' `;
			flag++;
		}
		if (req.body.mailtype || req.body.mailtype == 0) {
			if (where.trim().length === 0) {
				where += 'where ';
			}
			if (flag > 0) {
				where += ' and ';
			}
			where += ` mailtype = '${req.body.mailtype}' `;
			flag++;
		}
		if (req.body.sort) {
			where += ` order by pprice ${req.body.sort} `;
		}

		// if (where.trim().length === 0) {
		// 	where += 'where ';
		// }
		// if (flag > 0) {
		// 	where += ' and ';
		// }
		// where += ` p.state = 1 `;
	}
	dao.getCount(where)
		.then((count) => {
			console.log('count', count);
			pager.setCount(count);
			return dao.findByPage(where);
		})
		.then((data) => {
			console.log('data', data);
			pager.data = data;
			res.json({
				code: 200,
				data: pager,
			});
		})
		.catch((err) => next(err));
});

router.get('/getlist.do', (req, res, next) => {
	let { pid } = req.query;
	if (pid) {
		// let editObj = books.find(value => value.id == id);
		dao.findBy(pid)
			.then((data) => {
				if (data) {
					res.json({
						code: 200,
						data: data,
					});
				} else {
					res.json({
						code: 404,
						msg: '没有找到记录！',
					});
				}
			})
			.catch((err) => next(err));
	} else {
		res.json({
			code: 404,
			msg: '没有id！',
		});
	}
});

router.get('/del.do', (req, res, next) => {
	// lodash.remove(books, value => value.id == req.query.id);
	if (req.query.id) {
		dao.deleteById(req.query.id)
			.then((data) =>
				res.json({
					code: 200,
					msg: '删除成功',
				})
			)
			.catch((err) => next(err));
	} else {
		res.json({
			code: 200,
			msg: '删除失败',
		});
	}
});
router.get('/delBatch.do', (req, res, next) => {
	let idsStr = req.query.ids;
	console.log(idsStr);
	let ids;
	if (Array.isArray(idsStr)) {
		ids = idsStr;
	} else {
		ids = idsStr.split(','); //得到的是一个字符串数组
	}

	dao.deleteByIds(ids)
		.then((data) =>
			res.json({
				code: 200,
				msg: '删除成功',
			})
		)
		.catch((err) => next(err));
});

router.get('/edit.do', (req, res, next) => {
	let { id } = req.query;
	if (id) {
		dao.findById(id)
			.then((editObj) => {
				if (editObj) {
					res.json({
						code: 200,
						data: editObj,
					});
				} else {
					res.json({
						code: 404,
						msg: '没有找到记录！',
					});
				}
			})
			.catch((err) => next(err));
	} else {
		res.json({
			code: 404,
			msg: '没有id！',
		});
	}
});
router.post('/save.do', upload.single('file'), (req, res, next) => {
	if (req.body.__proto__ === undefined) Object.setPrototypeOf(req.body, new Object());
	let newObj = Object.assign({}, req.body);
	//区分添加还是编辑
	if (newObj.id) {
		//编辑
		// let editObj = books.find(value => value.id == newObj.id);
		// //引用数据类型的特点
		// Object.assign(editObj, newObj);
		dao.update(newObj, newObj.id)
			.then((data) =>
				res.json({
					code: 200,
					msg: '修改成功',
				})
			)
			.catch((err) => next(err));
	} else {
		//添加
		// // books.pop();删除最后一个元素
		// newObj.id = lodash.last(books).id + 1;
		// //保存到数组中
		// books.push(newObj);
		newObj.id = 0; //id是自动增长，必须是0值
		newObj.ppicture = fileAddress;
		dao.insert(newObj)
			.then((data) =>
				res.json({
					code: 200,
					msg: '添加成功',
				})
			)
			.catch((err) => next(err));
	}
});

router.post('/setselled.do', (req, res, next) => {
	if (req.body.__proto__ === undefined) Object.setPrototypeOf(req.body, new Object());
	let newObj = Object.assign({}, req.body);
	//区分添加还是编辑
		//编辑
		newObj.selled=1;
		dao.update(newObj, newObj.id)
			.then((data) =>
				res.json({
					code: 200,
					msg: '修改成功',
				})
			)
			.catch((err) => next(err));
});

router.get('/pay.do', (req, res, next) => {
	let { id, num } = req.query;
	if (id) {
		dao.findById(id)
			.then((editObj) => {
				if (editObj.pnum - num >= 0) {
					editObj.pnum = editObj.pnum - num;
					dao.update(editObj, editObj.id)
						.then((data) =>
							res.json({
								code: 200,
								msg: '购买成功',
							})
						)
						.catch((err) => next(err));
				} else {
					res.json({
						code: 500,
						msg: '库存不足',
					});
				}
			})
			.catch((err) => next(err));
	} else {
		res.json({
			code: 404,
			msg: '没有id！',
		});
	}
});
module.exports = router;
